package com.example.roamio.service.impl;

import com.example.roamio.common.Result;
import com.example.roamio.dto.EmailRegisterDTO;
import com.example.roamio.dto.EmailPasswordDTO;
import com.example.roamio.entity.User;
import com.example.roamio.repository.UserRepository;
import com.example.roamio.service.AuthService;
import com.example.roamio.util.RedisKeyUtil;
import com.example.roamio.util.TokenUtil;
import com.example.roamio.common.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final StringRedisTemplate redisTemplate;
    private final JavaMailSender mailSender;
    private final UserRepository userRepository;

    /**
     * 发送验证码邮件（保存在 Redis 中）
     */
    @Override
    public Result<String> sendCode(String email) {
        String code = String.format("%06d", new Random().nextInt(999999));
        redisTemplate.opsForValue().set(
                RedisKeyUtil.loginCodeKey(email), code, 5, TimeUnit.MINUTES
        );

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(email);
        message.setFrom("2541102169@qq.com");
        message.setSubject("Roamio 注册验证码");
        message.setText("您的验证码是：" + code + "，5分钟内有效。");
        mailSender.send(message);
        System.out.println("本次的验证码为"+code);

        return Result.success("验证码发送成功");
    }

    /**
     * 注册：邮箱 + 验证码 + 密码（验证码从 Redis 验证）
     */
    @Override
    public Result<String> register(EmailRegisterDTO dto) {
        if (userRepository.findByEmail(dto.getEmail()).isPresent()) {
            throw new BusinessException(400, "该邮箱已注册");
        }

        String cacheCode = redisTemplate.opsForValue().get(RedisKeyUtil.loginCodeKey(dto.getEmail()));
        if (cacheCode == null || !cacheCode.equals(dto.getCode())) {
            throw new BusinessException(400, "验证码错误或已过期");
        }

        User user = new User();
        user.setEmail(dto.getEmail());
        user.setUsername("用户" + dto.getEmail().hashCode());
        user.setPassword(dto.getPassword()); // 实际项目应加密处理
        userRepository.save(user);

        redisTemplate.delete(RedisKeyUtil.loginCodeKey(dto.getEmail()));
        return Result.success("注册成功");
    }

    /**
     * 登录：邮箱 + 密码
     */
    @Override
    public Result<String> loginByPassword(EmailPasswordDTO dto) {
        User user = userRepository.findByEmail(dto.getEmail())
                .orElseThrow(() -> new BusinessException(401, "用户不存在"));

        if (!user.getPassword().equals(dto.getPassword())) {
            throw new BusinessException(403, "密码错误");
        }

        String token = TokenUtil.generateToken();
        redisTemplate.opsForValue().set(
                RedisKeyUtil.tokenKey(token), String.valueOf(user.getUserId()), 30, TimeUnit.MINUTES
        );
        System.out.println("用户登录成功：email = " + user.getEmail() + "，userId = " + user.getUserId() + "，token = " + token);
        return Result.success(token);
    }
}
